package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.User;
import com.cskaoyan.exception.CustomValidationException;
import com.cskaoyan.util.ValidationUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author stone
 * @date 2022/01/03 16:36
 */
@RestController
@RequestMapping("user")
public class UserController {

    //localhost:8080/user/register?username=songge&password=niupi&age=30
    @RequestMapping("register")
    public BaseRespVo register(String username,String password,Integer age) {
        if (username == null || username.length() < 6) {
            return BaseRespVo.fail("username不合法");
        }
        if (password == null || password.length() < 6) {
            return BaseRespVo.fail("password不合法");
        }
        if (age == null || age < 18 || age > 100) {
            return BaseRespVo.fail("age不合法");
        }
        return BaseRespVo.ok();
    }

    //localhost:8080/user/register2?username=songge&password=niupi&age=30
    @RequestMapping("register2")
    public BaseRespVo register2(@Validated User user, BindingResult bindingResult) {
        return BaseRespVo.ok();
    }

    //在形参中增加一个BindingResult
    //localhost:8080/user/register3?username=songge&password=niupi&age=30
    @RequestMapping("register3")
    public BaseRespVo register3(@Validated User user, BindingResult bindingResult) {
        //如何知道校验没有通过
        if (bindingResult.hasFieldErrors()) {//只要有一个成员变量没有通过校验，返回true
            //如果校验没有通过是谁导致的 → 获得校验错误
            FieldError fieldError = bindingResult.getFieldError();
            //校验没有通过我们能获得哪些信息
            String field = fieldError.getField();//获得成员变量名 → 请求参数名
            Object rejectedValue = fieldError.getRejectedValue();//导致校验失败的值
            String defaultMessage = fieldError.getDefaultMessage();
            String msg = "请求参数" + field + "没有通过校验：" + rejectedValue + "; " + defaultMessage;
            return BaseRespVo.fail(msg);
        }
        return BaseRespVo.ok();
    }

    @RequestMapping("register4")
    public BaseRespVo register4(@Validated User user, BindingResult bindingResult) {

        if (bindingResult.hasFieldErrors()) {
            return ValidationUtil.validateResult(bindingResult);
        }
        return BaseRespVo.ok();
    }
    @RequestMapping("register5")
    public BaseRespVo register5(@Validated User user, BindingResult bindingResult) throws CustomValidationException {

        //如果没有校验成功是要响应Json数据的
        ValidationUtil.validate2(bindingResult);
        //toDo  业务
        return BaseRespVo.ok();
    }
}
